package com.artnology.independence.views;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.swt.widgets.Display;

import com.artnology.independence.Activator;
import com.artnology.independence.model.DVNode;

public class FindTypeInGraphHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		InputDialog dialog = new InputDialog(Display.getCurrent()
				.getActiveShell(), "Find type in graph",
				"Enter precise type name or use *", "", new IInputValidator() {

					@Override
					public String isValid(String input) {
						if (input.isEmpty()) {
							return null;
						}

						// first try exact match
						DVNode foundType = Activator.getDefault().getModel()
								.getTypeForSimpleNameIgnoreCase(input);
						if (foundType != null
								&& DependencyView.getView()
										.getDependencyViewer().getGraph()
										.containsVertex(foundType)) {
							DependencyView.getView().getDependencyViewer()
									.centerViewerOnNode(foundType);
							return null;
						}

						// secondly try pattern match
						input = input.toLowerCase();
						input = input.replace("*", ".*");
						Pattern pattern = Pattern.compile(input);
						Matcher matcher = null;
						for (DVNode dvType : Activator.getDefault().getModel()
								.getAllTypes()) {
							matcher = pattern.matcher(dvType.getName()
									.toLowerCase());
							if (matcher.find()
									&& DependencyView.getView()
											.getDependencyViewer().getGraph()
											.containsVertex(dvType)) {
								DependencyView.getView().getDependencyViewer()
										.centerViewerOnNode(dvType);
								return null;
							}
						}

						return "Can't find type in graph";
					}
				});

		dialog.open();
		return null;
	}

}
